package com.reform.config;

import com.reform.exception.MyException;
import com.reform.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * AuthorityInterceptor 拦截器
 */
@Slf4j
@Configuration
public class AuthorityInterceptor implements HandlerInterceptor {

    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    RedisUtils redisUtils;

    @Value("${jwt.expireTime}")
    Long expireTime;

    /**
     * 前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        log.info("拦截"+request.getRequestURI());
        //判断请求方式，排除OPTIONS请求
        if(request.getMethod().toUpperCase().equals("OPTIONS")){
            return true;//通过所有OPTION请求
        }
        String token = request.getHeader("token");
        if (token==null || token.equals("")){
            throw new MyException("请先登录");
        }
        String jsession_id = request.getHeader("jsession_id");
        if (jsession_id==null || jsession_id.equals("")){
            throw new MyException("请先登录");
        }
        String ghFromToken = jwtTokenUtil.getGHFromToken(token);
        Integer typeFromToken = jwtTokenUtil.getTypeFromToken(token);
        String uuidFromToken = jwtTokenUtil.getUUIDFromToken(token);

        //工号为空
        if (ghFromToken == null || ghFromToken.equals("")){
            throw new MyException("请重新登录");
        }
        //类型为空
        if (typeFromToken == null || typeFromToken.equals("")){
            throw new MyException("请重新登录");
        }
        //机器码为空
        if (uuidFromToken == null || uuidFromToken.equals("")){
            throw new MyException("请重新登录");
        }
        //授权异常
        if (!jsession_id.equals(uuidFromToken)){
            throw new MyException("授权异常,请重新登录");
        }

        String redisToken = (String) redisUtils.get(uuidFromToken);
        if (redisToken == null){
            throw new MyException("请重新登录");
        }
        //客户端token与redis不匹配
        if (!redisToken.equals(token)){
            throw new MyException("请重新登录");
        }
        //redis 找不到token
        if (redisUtils.get(uuidFromToken) == null || redisUtils.get(uuidFromToken).equals("")){
            throw new MyException("请重新登录");
        }
        long expire = redisUtils.getExpire(uuidFromToken);
        if (expire<=0){
            throw new MyException("请重新登录");
        }else {
            redisUtils.expire(jsession_id,expireTime);
        }
        log.info("成功通行"+request.getRequestURI());
        return true;
    }
}
